
/**
 * Module dependencies.
 */

const logger = require('koa-logger');
const serve = require('koa-static');
const koaBody = require('koa-body');
const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
const os = require('os');
const path = require('path');

// log requests

app.use(logger());

// maxFileSize 设置上传文件大小最大限制，默认2M

try {
  app.use(koaBody({ multipart: true, formidable: {maxFileSize: 2*1024*1024} }));

  
  // custom 404

  app.use(async function(ctx, next) {
    await next();
    if (ctx.body || !ctx.idempotent) return;
    ctx.redirect('/404.html');
  });

  // serve files from ./public

  app.use(serve(path.join(__dirname, '/public')));

  // handle uploads

  app.use(async function(ctx, next) {
    // ignore non-POSTs
    if ('POST' != ctx.method) return await next();

    const file = ctx.request.files.file;
    const extname = path.extname(file.name);	 //获取文件的后缀名
    console.log('文件后缀：', extname);
    const reader = fs.createReadStream(file.path);
    const stream = fs.createWriteStream(path.join(__dirname, Math.random().toString()+extname));
    reader.pipe(stream);
    console.log('uploading %s -> %s', file.name, stream.path);

    ctx.redirect('/');
  });

} catch (error) {
  console.log('文件超过限定大小');
}


// listen

app.listen(3000);
console.log('listening on port 3000');
